package com.nuatar.meibi;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.nuatar.meibi.pubvar.MyMsg;
import com.nuatar.meibi.pubvar.NetBus;
import com.nuatar.meibi.pubvar.PhoneMaster;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class MessageService extends Service {
	
	class MHandler extends Handler{
		@Override
		public void handleMessage(Message msg) {
			if(msg.what>0){
				NotificationManager nm = (NotificationManager) getBaseContext()
						.getSystemService(Context.NOTIFICATION_SERVICE);
				Intent intent1 = new Intent(getBaseContext(), MessageCenter.class);
				PendingIntent pd = PendingIntent.getActivity(getBaseContext(), 0,
						intent1, Intent.FLAG_ACTIVITY_NEW_TASK);
				Notification nf = new Notification();
				nf.icon = R.drawable.ic_launcher;
				nf.tickerText = "美库消息！";
				nf.defaults = Notification.DEFAULT_SOUND;
				nf.defaults |= Notification.DEFAULT_VIBRATE;
				nf.defaults |= Notification.DEFAULT_LIGHTS;
				nf.flags = Notification.FLAG_AUTO_CANCEL;
				nf.setLatestEventInfo(getBaseContext(), "美库给你发来消息",
						"一共有" + msg.what + "条消息", pd);
				nm.notify(110, nf);
			}
			stopSelf();
		}
	}
	public static MHandler mhandler;
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void onCreate() {
		super.onCreate();
		mhandler=new MHandler();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		MT mt = new MT();
		new Thread(mt).start();
		return START_NOT_STICKY;
	}

	@Override
	public void onDestroy() {
		this.stopSelf();
		super.onDestroy();
	}

	class MT implements Runnable {
		@Override
		public void run() {
			// TODO Auto-generated method stub
			SharedPreferences pre = PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext());
			String MsgKey="MsgTime";
			String msgtime=pre.getString(MsgKey, "20130101000000");
			TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
			String did = PhoneMaster.getMD5Str(telephonyManager.getDeviceId());
			List<MyMsg> list=new ArrayList<MyMsg>();
			list=NetBus.getMessage(did,msgtime);
			if(list!=null){
				MessageService.mhandler.sendEmptyMessage(list.size());
			}
			
		}
	}
}
